<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- ../src/examples/cachedtable.qdoc -->
<head>
  <title>Cached Table Example</title>
    <style type="text/css">h3.fn,span.fn { margin-left: 1cm; text-indent: -1cm; }
a:link { color: #004faf; text-decoration: none }
a:visited { color: #672967; text-decoration: none }
td.postheader { font-family: sans-serif }
tr.address { font-family: sans-serif }
body { color: black; }</style>
</head>
<body>
<h1 class="title">Cached Table Example<br /><span class="subtitle"></span>
</h1>
<p>The Cached Table example shows how a table view can be used to access a database, caching any changes to the data until the user explicitly submits them using a push button.</p>
<p align="center"><img src="classpath:com/trolltech/images/cachedtable-example.png" /></p><p>The example consists of a single class, <tt>TableEditor</tt>, which is a custom dialog widget that allows the user to modify data stored in a database. We will first review the class definiton and how to use the class, then we will take a look at the implementation.</p>
<a name="cachedtable-class-implementation"></a>
<h2>CachedTable Class Implementation</h2>
<p>The <tt>CachedTable</tt> class inherits QDialog making the table editor widget a top-level dialog window.</p>
<pre>    public class CachedTable extends QDialog {
        private QPushButton submitButton = null;
        private QPushButton revertButton = null;
        private QPushButton quitButton = null;
        private QSqlTableModel model = null;</pre>
<p>Note the QSqlTableModel variable declaration: As we will see in this example, the QSqlTableModel class can be used to provide data to view classes such as QTableView. The QSqlTableModel class provides an editable data model making it possible to read and write database records from a single table. It is build on top of the lower-level QSqlQuery class which provides means of executing and manipulating SQL statements.</p>
<p>We define a static method to check for suitable database support:</p>
<pre>        public static boolean checkSqlLite() {
            return QSqlDatabase.isDriverAvailable(&quot;QSQLITE&quot;);
        }</pre>
<p>We are also going to show how a table view can be used to cache any changes to the data until the user explicitly requests to submit them. For that reason we need to declare a <tt>submit()</tt> slot in additon to the model and the editor's buttons.</p>
<p><table width="100%" align="center" cellpadding="2" cellspacing="1" border="0">
<thead><tr valign="top" class="qt-style"><th>Connecting to a Database</th></tr></thead>
<tr valign="top" class="odd"><td>Before we can use the <tt>CachedTable</tt> class, we must create a connection to the database containing the table we want to edit. We do this by defining a <tt>SqlCommon</tt> class containing a method that performs this task:<pre>    class SqlCommon
    {
        static boolean createConnection()
        {
            QSqlDatabase db = QSqlDatabase.addDatabase(&quot;QSQLITE&quot;, &quot;qt_sql_default_connection&quot;);
            db.setDatabaseName(&quot;:memory:&quot;);
            if (!db.open()) {
                QMessageBox.critical(null, QApplication.instance().tr(&quot;Cannot open database&quot;),
                    QApplication.instance().tr(&quot;Unable to establish a database connection.\n&quot; +
                             &quot;This example needs SQLite support. Please read &quot; +
                             &quot;the Qt SQL driver documentation for information how &quot; +
                             &quot;to build it.\n\n&quot; +
                             &quot;Click Cancel to exit.&quot;),
                             new QMessageBox.StandardButtons(QMessageBox.StandardButton.Cancel,
                                                             QMessageBox.StandardButton.NoButton));
                return false;
            }

            QSqlQuery query = new QSqlQuery();
            query.exec(&quot;create table person (id int primary key, &quot; +
                       &quot;firstname varchar(20), lastname varchar(20))&quot;);
            query.exec(&quot;insert into person values(101, 'Danny', 'Young')&quot;);
            query.exec(&quot;insert into person values(102, 'Christine', 'Holand')&quot;);
            query.exec(&quot;insert into person values(103, 'Lars', 'Gordon')&quot;);
            query.exec(&quot;insert into person values(104, 'Roberto', 'Robitaille')&quot;);
            query.exec(&quot;insert into person values(105, 'Maria', 'Papadopoulos')&quot;);

            return true;

        }
    }</pre>
<p>The <tt>createConnection()</tt> method is a helper method provided for convenience. It opens a connection to an in-memory SQLITE database and creates a test table. If you want to use another database, simply modify this method's code.</p>
</td></tr>
</table></p>
<p>Apart from the static <tt>checkSqlLite()</tt> method, the class implementation consists of only the constructor and the <tt>submit()</tt> slot. In the constructor we create and customize the data model and the various window elements:</p>
<pre>        public CachedTable(QWidget parent)
        {
            super(parent);

            if (!SqlCommon.createConnection())
                throw new RuntimeException(&quot;Couldn't connect to SQLITE server&quot;);</pre>
<p>First we create the data model and set the SQL database table we want the model to operate on. Note that the QSqlTableModel::setTable() method does not select data from the table; it only fetches its field information. For that reason we call the QSqlTableModel::select() method later on, populating the model with data from the table. The selection can be customized by specifying filters and sort conditions (see the QSqlTableModel class documentation for more details).</p>
<pre>            model = new QSqlTableModel(this);
            model.setTable(tableName);
            model.setEditStrategy(QSqlTableModel.EditStrategy.OnManualSubmit);
            model.select();

            model.setHeaderData(0, Qt.Orientation.Horizontal, tr(&quot;ID&quot;));
            model.setHeaderData(1, Qt.Orientation.Horizontal, tr(&quot;First name&quot;));
            model.setHeaderData(2, Qt.Orientation.Horizontal, tr(&quot;Last name&quot;));</pre>
<p>We also set the model's edit strategy: The edit strategy dictates when the changes done by the user in the view are actually applied to the database. Since we want to cache the changes in the table view (i.e&#x2e; in the model) until the user explicitly submits them, we choose the QSqlTableModel::OnManualSubmit strategy. The alternatives are QSqlTableModel::OnFieldChange and QSqlTableModel::OnRowChange.</p>
<p>Finally, we set up the labels displayed in the view header using the setHeaderData() method the model inherits from the QSqlQueryModel class.</p>
<pre>            QTableView view = new QTableView();
            view.setModel(model);</pre>
<p>Then we create a table view. The QTableView class provides a default model/view implementation of a table view, i.e&#x2e; it implements a table view that displays items from a model. It also allows the user to edit the items, storing the changes in the model. To create a read only view, set the proper flag using the editTriggers property the view inherits from the QAbstractItemView class.</p>
<p>We pass our model to the view, using the setModel() method, to make the view present our data.</p>
<pre>            submitButton = new QPushButton(tr(&quot;Submit&quot;));
            submitButton.setDefault(true);
            revertButton = new QPushButton(tr(&quot;&amp;Revert&quot;));
            quitButton = new QPushButton(tr(&quot;Quit&quot;));

            submitButton.clicked.connect(this, &quot;submit()&quot;);
            revertButton.clicked.connect(model, &quot;revertAll()&quot;);
            quitButton.clicked.connect(this, &quot;close()&quot;);</pre>
<p>The <tt>TableEditor</tt>'s buttons are regular QPushButton objects. We connect the <b>Quit</b> button to the table editor's close() slot, and the <b>Submit</b> button to our private <tt>submit()</tt> slot. The latter slot will take care of the data transactions. Finally, we connect the <b>Revert</b> button to our model's revertAll() slot, reverting all pending changes (restoring the original data).</p>
<pre>            QVBoxLayout buttonLayout = new QVBoxLayout();
            buttonLayout.addWidget(submitButton);
            buttonLayout.addWidget(revertButton);
            buttonLayout.addWidget(quitButton);
            buttonLayout.addStretch(1);

            QHBoxLayout mainLayout = new QHBoxLayout();
            mainLayout.addWidget(view);
            mainLayout.addLayout(buttonLayout);
            setLayout(mainLayout);

            setWindowTitle(tr(&quot;Cached Table&quot;));
        }</pre>
<p>In the end we add all the buttons and the table view to a layout, install the layout on the table editor widget, and set the editor's window title.</p>
<pre>        protected void submit()
        {
            model.database().transaction();
            if (model.submitAll()) {
                model.database().commit();
            } else {
                model.database().rollback();
                QMessageBox.warning(this, tr(&quot;Cached Table&quot;),
                                    tr(&quot;The database reported an error: &quot;) + model.lastError().text());
            }
        }</pre>
<p>The <tt>submit()</tt> slot is called whenever the users hit the <b>Submit</b> button to save their changes.</p>
<p>First, we begin a transaction on the database using the QSqlDatabase::transaction() method. A database transaction is a unit of interaction with a database management system or similar system that is treated in a coherent and reliable way independent of other transactions. A pointer to the used database can be obtained using the QSqlTableModel::database() method.</p>
<p>Then, we try to submit all the pending changes, i.e&#x2e; the model's modified items. If no error occurs, we commit the transaction to the database using the QSqlDatabase::commit() method (note that on some databases, this method will not work if there is an active QSqlQuery on the database). Otherwise we perform a rollback of the transaction using the QSqlDatabase::rollback() method and post a warning to the user.</p>
<p><table width="100%" align="center" cellpadding="2" cellspacing="1" border="0">
<tr valign="top" class="odd"><td><b>See also:</b><p>A complete list of Qt's SQL Database Classes, and the Model/View Programming documentation.</p>
</td></tr>
</table></p>
</body>
</html>
